package com.eii.gateway.filter;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.eii.gateway.utils.ReactiveAddrUtil;
import com.eii.log.monitor.PointUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * 请求统计分析埋点过滤器
 */
@Component
public class RequestStatisticsFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        Map<String, String> headers = request.getHeaders().toSingleValueMap();
        UserAgent ua = UserAgentUtil.parse(headers.get("User-Agent"));
        String browser = ua.getBrowser().toString();//Chrome
        // String browserVersion = ua.getVersion();//14.0.835.163
        // String engine = ua.getEngine().toString();//Webkit
        // String engineVersion = ua.getEngineVersion();//535.1
        String operatingSystem = ua.getOs().toString();//Windows 7
        // String platform = ua.getPlatform().toString();//Windows
        Boolean isMobile = ua.isMobile();
        //埋点
        PointUtil.debug("1", "request-statistics",
                "ip=" + ReactiveAddrUtil.getRemoteAddr(request)
                        + "&browser=" + browser
                        + "&operatingSystem=" + operatingSystem
                        + "&isMobile=" + isMobile.toString())
        ;

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
